package com.pactera.madp.cp.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.security.util.SecurityUtils;
import com.pactera.madp.cp.api.dto.workroom.WorkContactRoomIndexDto;
import com.pactera.madp.cp.api.dto.workroom.WorkRoomIndexDto;
import com.pactera.madp.cp.api.dto.workroom.WorkRoomStatisticsIndexDto;
import com.pactera.madp.cp.api.em.permission.ReqPerEnum;
import com.pactera.madp.cp.api.em.workcontactroom.JoinSceneEnum;
import com.pactera.madp.cp.api.em.workcontactroom.Status;
import com.pactera.madp.cp.api.em.workupdatetime.TypeEnum;
import com.pactera.madp.cp.api.entity.*;
import com.pactera.madp.cp.api.entity.workroom.WorkRoomGroupEntity;
import com.pactera.madp.cp.api.feign.RemoteDeptService;
import com.pactera.madp.cp.api.model.WorkRoomIndexRespModel;
import com.pactera.madp.cp.api.model.workroom.*;
import com.pactera.madp.cp.api.page.SubPage;
import com.pactera.madp.cp.api.vo.taskpublish.GroupChatVO;
import com.pactera.madp.cp.api.vo.workroom.WorkRoomDataStatisticsVO;
import com.pactera.madp.cp.api.vo.workroom.WorkRoomPageVO;
import com.pactera.madp.cp.common.util.DateUtils;
import com.pactera.madp.cp.common.util.PageUtil;
import com.pactera.madp.cp.common.util.WxApiUtils;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.WorkContactRoomMapper;
import com.pactera.madp.cp.mapper.workroom.WorkRoomMapper;
import com.pactera.madp.cp.service.*;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:客户群
 * @author: Huayu
 * @time: 2020/12/8 14:42
 */
@Service
@Slf4j
public class WorkRoomServiceImpl extends ServiceImpl<WorkRoomMapper, WorkRoomEntity> implements IWorkRoomService {

    @Autowired
    private WorkRoomMapper workRoomMapper;
    @Autowired
    private IWorkEmployeeService workEmployeeServiceImpl;
    @Autowired
    private IWorkRoomGroupService roomGroupService;
    @Autowired
    private IWorkContactRoomService workContactRoomServiceImpl;
    @Autowired
    private IWorkContactService workContactServiceImpl;
    @Autowired
    private ICorpService corpServiceImpl;
    @Autowired
    private IWorkEmployeeDepartmentService employeeDepartmentService;
    @Autowired
    private IWorkUpdateTimeService workUpdateTimeService;
    @Autowired
    private RemoteDeptService remoteDeptService;
    @Autowired
    private IWorkEmployeeService employeeService;
    @Autowired
    private WorkContactRoomMapper workContactRoomMapper;

    @Override
    @Transactional
    public Integer updateWorkRoomsByRoomGroupId(Integer workRoomGroupId, int roomGroupId) {
        Map<String, Object> map = new HashMap<>();
        map.put("workRoomGroupId", workRoomGroupId);
        map.put("roomGroupId", roomGroupId);
        return baseMapper.updateWorkRoomsByRoomGroupId(map);
    }

    @Override
    public R getWorkRoomList(WorkRoomIndexDto req, ReqPerEnum permission, Page page) {
//        Page<WorkRoomEntity> roomEntityPage = ApiRespUtils.initPage(req);
        LambdaQueryChainWrapper<WorkRoomEntity> wrapper = lambdaQuery().eq(WorkRoomEntity::getCorpId, AccountService.getCorpId())
                .eq(WorkRoomEntity::getRoomStatus,0);
        wrapper.orderByDesc(WorkRoomEntity::getCreateTime);
        if (Objects.nonNull(req.getEmployeeId())) {
            wrapper.eq(WorkRoomEntity::getOwnerId, req.getEmployeeId());
        }
        if (Objects.nonNull(req.getRoomGroupId())) {
            wrapper.eq(WorkRoomEntity::getRoomGroupId, req.getRoomGroupId());
        }
        if (Objects.nonNull(req.getWorkRoomName()) && !req.getWorkRoomName().isEmpty()) {
            wrapper.like(WorkRoomEntity::getName, req.getWorkRoomName());
        }

        if (Objects.nonNull(req.getWorkRoomStatus()) && req.getWorkRoomStatus() >= 0 && req.getWorkRoomStatus() <= 3) {
            wrapper.eq(WorkRoomEntity::getStatus, req.getWorkRoomStatus());
        }
        if (Objects.nonNull(req.getStartTime()) && !req.getStartTime().isEmpty()) {
            wrapper.ge(WorkRoomEntity::getCreateTime, req.getStartTime());
        }
        if (req.getEndTime() != null && !req.getEndTime().isEmpty()) {
            wrapper.le(WorkRoomEntity::getCreateTime, req.getEndTime());
        }
        if (Objects.nonNull(req.getWorkRoomOwner()) && !StringUtil.isBlank(req.getWorkRoomOwner())){
            List<WorkEmployeeEntity> list = workEmployeeServiceImpl.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                    .like(WorkEmployeeEntity::getName, req.getWorkRoomOwner()));
            Integer linkedList[] = new Integer[list.size()];
            for (int i = 0; i < list.size(); i++) {
                linkedList[i] = list.get(i).getId();
            }
            if (linkedList.length != 0){
                wrapper.in(WorkRoomEntity::getOwnerId,linkedList);
            }else {
                wrapper.eq(WorkRoomEntity::getOwnerId,0);
            }
        }

        // 权限管理数据过滤
        if (Objects.nonNull(req.getWorkRoomOwnerId()) && !req.getWorkRoomOwnerId().isEmpty()) {
            List<String> ownerIdList = Arrays.asList(req.getWorkRoomOwnerId().split(","));
            setWrapperPermission(wrapper, ownerIdList, permission);
        } else {
            setWrapperPermission(wrapper, Collections.EMPTY_LIST, permission);
        }
        wrapper.page(page);

        List<WorkRoomEntity> workRoomEntityList = page.getRecords();

        List<WorkRoomIndexRespModel> voList = new ArrayList<>();

        String currentDayStr = DateUtils.getDateByS3();
        String currentDayStartStr = DateUtils.getDateOfDayStartByS3(currentDayStr);
        String currentDayEndStr = DateUtils.getDateOfDayEndByS3(currentDayStr);
        long currentDayStartMillis = DateUtils.getMillsByS1(currentDayStartStr);
        long currentDayEndMillis = DateUtils.getMillsByS1(currentDayEndStr);

        //处理列表数据
        for (WorkRoomEntity entity : workRoomEntityList) {
            //群主信息
            WorkEmployeeEntity workEmployee = workEmployeeServiceImpl.getById(entity.getOwnerId());
            if (Objects.isNull(workEmployee)){
                continue;
            }

            WorkRoomIndexRespModel workRoomIndexRespModel = new WorkRoomIndexRespModel();
            workRoomIndexRespModel.setOwnerName(workEmployee.getName());
            // 群成员数量统计
            List<WorkContactRoomEntity> contactRoomEntityList = workContactRoomServiceImpl.getWorkContactRoomsByRoomId(entity.getId());
            // 群成员数量
            Integer memberNum = 0;
            // 今日入群数量
            Integer inRoomNum = 0;
            // 今日退群数量
            Integer outRoomNum = 0;
            if (contactRoomEntityList.size() > 0) {
                for (WorkContactRoomEntity workContactRoomEntity : contactRoomEntityList) {
                    if (workContactRoomEntity.getStatus().equals(1)) {
                        memberNum++;
                    }
                    long joinTime = workContactRoomEntity.getJoinTime().getTime();
                    if (joinTime >= currentDayStartMillis && joinTime <= currentDayEndMillis) {
                        inRoomNum++;
                    }
                    String outTimeStr = workContactRoomEntity.getOutTime();
                    if (Objects.nonNull(outTimeStr) && !outTimeStr.isEmpty()) {
                        long outTime = DateUtils.getMillsByS1(outTimeStr);
                        if (outTime >= currentDayStartMillis && outTime <= currentDayEndMillis) {
                            outRoomNum++;
                        }
                    }
                }
            }
            //组装list数据
            workRoomIndexRespModel.setWorkRoomId(entity.getId());
            workRoomIndexRespModel.setMemberNum(memberNum);
            workRoomIndexRespModel.setRoomName(entity.getName());

            WorkRoomGroupEntity roomGroupEntity = roomGroupService.lambdaQuery()
                    .select(WorkRoomGroupEntity::getName)
                    .eq(WorkRoomGroupEntity::getId, entity.getRoomGroupId())
                    .one();
            if (Objects.nonNull(roomGroupEntity)) {
                workRoomIndexRespModel.setRoomGroup(roomGroupEntity.getName());
            }

            workRoomIndexRespModel.setStatus(entity.getStatus());
            workRoomIndexRespModel.setStatusText(entity.getStatus() == 0 ? "正常" : "退群");
            workRoomIndexRespModel.setInRoomNum(inRoomNum);
            workRoomIndexRespModel.setOutRoomNum(outRoomNum);
            workRoomIndexRespModel.setNotice(entity.getNotice());
            workRoomIndexRespModel.setCreateTime(entity.getCreateTime());
            voList.add(workRoomIndexRespModel);

        }

        SubPage subPage = new SubPage();
        String syncWorkRoomTime = workUpdateTimeService.getLastUpdateTime(TypeEnum.WORK_ROOM);
        subPage.setRecords(voList);
        subPage.setCurrent(page.getCurrent());
        subPage.setSize(page.getSize());
        subPage.setTotal(page.getTotal());
        subPage.getExtraProps().put("syncWorkRoomTime",syncWorkRoomTime);
        return R.ok(subPage);
//        return ApiRespUtils.transPage(roomEntityPage, voList);
    }

    /**
     * @author: yangpengwei
     * @time: 2021/3/17 11:19 上午
     * @description 权限管理查询条件配置
     */
    private void setWrapperPermission(LambdaQueryChainWrapper<WorkRoomEntity> wrapper, List<String> ownerIdList, ReqPerEnum permission) {
        if (ownerIdList.isEmpty()) {
            if (permission == ReqPerEnum.ALL) {
                return;
            }

            if (permission == ReqPerEnum.DEPARTMENT) {
                // 查询员工所属的部门 id 列表
                List<Integer> idList = employeeDepartmentService.getDeptAndChildDeptEmpIdList();
                if (idList.isEmpty()) {
                    wrapper.eq(WorkRoomEntity::getOwnerId, -1);
                } else {
                    wrapper.in(WorkRoomEntity::getOwnerId, idList);
                }
                return;
            }

            if (permission == ReqPerEnum.EMPLOYEE) {
                int empId = AccountService.getEmpId();
                wrapper.eq(WorkRoomEntity::getOwnerId, empId);
                return;
            }
        } else {
            if (permission == ReqPerEnum.ALL) {
                wrapper.in(WorkRoomEntity::getOwnerId, ownerIdList);
                return;
            }

            if (permission == ReqPerEnum.DEPARTMENT) {
                // 查询员工所属的部门 id 列表
                List<Integer> idList = employeeDepartmentService.getDeptAndChildDeptEmpIdList();
                if (idList.isEmpty()) {
                    wrapper.eq(WorkRoomEntity::getOwnerId, -1);
                    return;
                }

                List<String> idListStr = idList.stream().map(integer -> "" + integer).collect(Collectors.toList());
                ownerIdList.retainAll(idListStr);
                if (ownerIdList.isEmpty()) {
                    wrapper.eq(WorkRoomEntity::getOwnerId, -1);
                } else {
                    wrapper.in(WorkRoomEntity::getOwnerId, ownerIdList);
                }
                return;
            }

            if (permission == ReqPerEnum.EMPLOYEE) {
                int empId = AccountService.getEmpId();
                if (ownerIdList.contains("" + empId)) {
                    wrapper.eq(WorkRoomEntity::getOwnerId, empId);
                } else {
                    wrapper.eq(WorkRoomEntity::getOwnerId, -1);
                }
            }
        }
    }

    @Override
    public WorkRoomEntity getWorkRoom(Integer workRoomId) {
        WorkRoomEntity workRoomEntity = this.baseMapper.selectById(workRoomId);
        return workRoomEntity;
    }

    @Override
    public List<GroupChatVO> getWorkRoomName() {
        List<WorkRoomEntity> list = this.list(Wrappers.<WorkRoomEntity>lambdaQuery().eq(WorkRoomEntity::getCorpId,CorpContextHolder.getCorpId()));
        List<GroupChatVO> VOS = new ArrayList<>();
        for(WorkRoomEntity entity:list){
            GroupChatVO vo = new GroupChatVO();
            vo.setId(entity.getId());
            vo.setCorpId(CorpContextHolder.getCorpId());
            vo.setChatId(entity.getWxChatId());
            vo.setName(entity.getName());
            vo.setOwnerId(entity.getOwnerId());
            VOS.add(vo);
        }
        return VOS;
    }
    @Override
    public List<GroupChatVO> getRoom() {
        List<WorkRoomEntity> list = this.list(Wrappers.<WorkRoomEntity>lambdaQuery().eq(WorkRoomEntity::getCorpId,CorpContextHolder.getCorpId()).eq(WorkRoomEntity::getRoomStatus, 1));
        List<GroupChatVO> VOS = new ArrayList<>();
        for(WorkRoomEntity entity:list){
            GroupChatVO vo = new GroupChatVO();
            vo.setId(entity.getId());
            vo.setCorpId(CorpContextHolder.getCorpId());
            vo.setChatId(entity.getWxChatId());
            vo.setName(entity.getName());
            vo.setOwnerId(entity.getOwnerId());
            VOS.add(vo);
        }
        return VOS;
    }

    @Override
    public String getNameById(Integer id) {
        WorkRoomEntity workRoomEntity = this.getById(id);
        String name = workRoomEntity.getName();
        return name;
    }

    @Override
    public String getUserId(Integer id) {
        WorkRoomEntity workRoomEntity = this.getById(id);
        String userId = workRoomEntity.getWxChatId();
        return userId;
    }

    @Override
    public R handelWorkContactRoomData(WorkRoomEntity workRoomEntity, WorkContactRoomIndexDto workContactRoomIndexDto, Page page) {
        WorkRoomEntity one = baseMapper.selectOne(Wrappers.<WorkRoomEntity>lambdaQuery()
                .eq(WorkRoomEntity::getId, workContactRoomIndexDto.getWorkRoomId())
                .eq(WorkRoomEntity::getCorpId,CorpContextHolder.getCorpId()));
        WorkEmployeeEntity implOne = workEmployeeServiceImpl.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery().eq(WorkEmployeeEntity::getId, one.getOwnerId()));
        WorkContactRoomIndex index = new WorkContactRoomIndex();
        index.setName(implOne.getName());
        //index.setAvatar(AliyunOssUtils.getUrl(implOne.getAvatar()));
        index.setAvatar(implOne.getAvatar());
        index.setOwnerFlag(1);

        List<WorkEmployeeEntity> workEmployeeEntityList = null;
        List<WorkContactEntity> workContactEntityList = null;
        String workEmployeeIds = "";
        String workContactIds = "";
        String hadName = "0";
        //处理客户群成员名称
        if (workContactRoomIndexDto.getName() != null) {
            //是否存在成员名称的模糊搜索
            hadName = "1";
            //企业通讯录成员模糊匹配
            workEmployeeEntityList = workEmployeeServiceImpl.getWorkEmployeesByCorpIdName(workRoomEntity.getCorpId(), workContactRoomIndexDto.getName(), "id,name,avatar,wx_user_id");
            //企业外部联系人模糊匹配
            workContactEntityList = workContactServiceImpl.getWorkContactsByCorpIdName(workRoomEntity.getCorpId(), workContactRoomIndexDto.getName(), "id,name,avatar,wx_external_userid");
            if (workEmployeeEntityList.size() == 0 && workContactEntityList.size() == 0) {
                workContactRoomIndexDto = null;
            } else {
                StringBuilder sb = new StringBuilder();
                StringBuilder sb1 = new StringBuilder();
                for (int i = 0; i < workEmployeeEntityList.size(); i++) {
                    sb.append(workEmployeeEntityList.get(i).getId()).append(",");
                }
                workEmployeeIds = workEmployeeEntityList.isEmpty() ? "" : sb.toString().substring(0, sb.toString().length() - 1);
                for (int i = 0; i < workContactEntityList.size(); i++) {
                    sb1.append(workContactEntityList.get(i).getId()).append(",");
                }
                workContactIds = workContactEntityList.isEmpty() ? "" : sb1.toString().substring(0, sb1.toString().length() - 1);

            }
        }

        return getContactRooms(workRoomEntity, workContactRoomIndexDto, workEmployeeIds, workContactIds, hadName, workEmployeeEntityList, workContactEntityList,page,index);
//        WorkContactRoomIndexResp workContactRoomIndexResp = getContactRooms(workRoomEntity, workContactRoomIndexDto, workEmployeeIds, workContactIds, hadName, workEmployeeEntityList, workContactEntityList);
//        if (workContactRoomIndexResp == null) {
//            return null;
//        }
//        return workContactRoomIndexResp;
    }

    /**
     * @description:通过roomIds找到对应的群名称
     * @return:
     * @author: Huayu
     * @time: 2020/12/17 14:25
     */
    @Override
    public List<WorkRoomEntity> getWorkRoomsByIds(String workContactRoomIds, String clStr) {
        QueryWrapper<WorkRoomEntity> workContactRoomEntity = new QueryWrapper<WorkRoomEntity>();
        workContactRoomEntity.select(clStr);
        List<String> typeList = new ArrayList<>();
        if (clStr != null) {
            String[] typeStr = workContactRoomIds.split(",");
            for (int i = 0; i < typeStr.length; i++) {
                typeList.add(typeStr[i]);
            }
        }
        workContactRoomEntity.in("id", typeList);
        return this.baseMapper.selectList(workContactRoomEntity);
    }


    /**
     * @description:同步客户群列表
     * @return:
     * @author: Huayu
     * @time: 2020/12/17 17:18
     */
    @Override
    public boolean syncWorkRoomIndex(Integer corpIds, List<WXWorkRoomModel> WXWorkRoomModelList, Integer isFlag) {
        CorpEntity corpEntity = corpServiceImpl.getCorpInfoById(corpIds);
        if (isFlag.equals(0)) {
            String result = WxApiUtils.getWorkRoomIndexData(corpEntity, null);
            if (result == null) {
                return false;
            }
            List<WXWorkRoomIdsModel> workRoomIdsModelList = JSONArray.parseArray(result, WXWorkRoomIdsModel.class);
            WXWorkRoomModelList = new ArrayList<WXWorkRoomModel>();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (WXWorkRoomIdsModel workRoomModelIds :
                    workRoomIdsModelList) {
                WXWorkRoomModel WXWorkRoomModel = new WXWorkRoomModel();
                WXWorkRoomModel.setChatId(workRoomModelIds.getChatId());
                WXWorkRoomModel.setStatus(workRoomModelIds.getStatus());
                //获取群聊详情
                String workRoomInfo = WxApiUtils.getWorkRoomInfoData(corpEntity, workRoomModelIds.getChatId());
                try {
                    //合并客户群和客户群详情数据
                    //取出member_list
                    JSONObject workRoomInfoJson = JSONObject.parseObject(workRoomInfo);
                    WXWorkRoomModel.setName(workRoomInfoJson.get("name").toString());//群名称
                    WXWorkRoomModel.setOwner(workRoomInfoJson.get("owner").toString());//群主id
                    String dateStr = null;
                    dateStr = DateUtils.formatS1(workRoomInfoJson.get("create_time") + "000");
                    Timestamp timestamp = Timestamp.valueOf(dateStr);
                    LocalDateTime createTime = timestamp.toLocalDateTime();
                    WXWorkRoomModel.setCreateTime(createTime);//创建时间
//                    WXWorkRoomModel.setCreateTime(LocalDateTime.parse(workRoomInfoJson.get("create_time")+ "000"));
                    WXWorkRoomModel.setNotice(workRoomInfoJson.get("notice") == null ? "" : workRoomInfoJson.get("notice").toString());//群公告
                    JSONArray jsonArray = workRoomInfoJson.getJSONArray("member_list");
                    List<WXWorkRoomInfoModel> resultInfoList = jsonArray.toJavaList(WXWorkRoomInfoModel.class);
                    WXWorkRoomModel.setWXWorkRoomInfoModel(resultInfoList);//群成员列表
                    WXWorkRoomModelList.add(WXWorkRoomModel);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //获取系统中当前企业所有客户群聊列表
        Map<String, Object> map = handelWXWorkRoomModelData(WXWorkRoomModelList, corpEntity.getCorpId(), isFlag);
        Map<String, Object> workContactRoomModelMap = (Map<String, Object>) map.get("roomList");
        Map<String, Object> employeeMap = (Map<String, Object>) map.get("employeeList");
        Map<String, Object> contactMap = (Map<String, Object>) map.get("contactList");
        //客户群-新增数据
        List<WorkRoomEntity> workRoomEntityCreateList = new ArrayList<WorkRoomEntity>();
        //客户群-更新数据
        List<WorkRoomEntity> workRoomEntityUpdateList = new ArrayList<WorkRoomEntity>();
        //客户群-删除数据
        String deleteContactRoomIdArr = null;
        //客户成员-新增数据
        List<WorkContactRoomEntity> workContactRoomEntityCreateList = new ArrayList<WorkContactRoomEntity>();
        List<WorkContactRoomEntity> workContactRoomEntityCreateListx = new ArrayList<WorkContactRoomEntity>();
        //客户成员-更新数据
        List<WorkContactRoomEntity> workContactRoomEntityUpdateList = new ArrayList<WorkContactRoomEntity>();
        //客户成员-删除数据
        String deleteRoomIdArr = null;
        for (WXWorkRoomModel WXWorkRoomModel : WXWorkRoomModelList) {

            WXWorkContactRoomModel currentRoomModel = null;
            WorkRoomEntity workRoomEntity = new WorkRoomEntity();
            if (workContactRoomModelMap.get(WXWorkRoomModel.getChatId()) != null) {
                currentRoomModel = (WXWorkContactRoomModel) workContactRoomModelMap.get(String.valueOf(WXWorkRoomModel.getChatId()));
                //群
                workRoomEntity.setId(currentRoomModel.getId());
                workRoomEntity.setStatus(WXWorkRoomModel.getStatus());
                workRoomEntity.setName(StringUtil.isBlank(WXWorkRoomModel.getName())? "群聊" : WXWorkRoomModel.getName());
                Integer owner = (Integer) employeeMap.get(WXWorkRoomModel.getOwner());
                if (owner == null){
                    continue;
                }
                workRoomEntity.setOwnerId(owner);
                workRoomEntity.setNotice(StringUtil.isBlank(WXWorkRoomModel.getNotice() )? "" : WXWorkRoomModel.getNotice());
                workRoomEntity.setCreateTime(WXWorkRoomModel.getCreateTime());
                workRoomEntityUpdateList.add(workRoomEntity);
                //删除Key
                workContactRoomModelMap.remove(WXWorkRoomModel.getChatId());
                //群成员
                List<WXWorkRoomInfoModel> WXWorkRoomInfoModelList = WXWorkRoomModel.getWXWorkRoomInfoModel();
                List<String> list = new LinkedList<>();
                for (WXWorkRoomInfoModel WXWorkRoomInfoModel :  WXWorkRoomInfoModelList) {
                    list.add(WXWorkRoomInfoModel.getUserid());
                    Integer contactId = 0;
                    Integer employeeId = 0;


                    if (WXWorkRoomInfoModel.getType().equals(1)) {
                        employeeId = employeeMap.get(WXWorkRoomInfoModel.getUserid()) != null ? (Integer) employeeMap.get(WXWorkRoomInfoModel.getUserid()) : 0;
                    } else {
                        contactId = contactMap.get(WXWorkRoomInfoModel.getUserid()) != null ? (Integer) contactMap.get(WXWorkRoomInfoModel.getUserid()) : 0;
                    }


                    if (currentRoomModel.getWXWorkContactRoomInfoModelListMap().get(WXWorkRoomInfoModel.getUserid().toString()) != null) {
                        WorkContactRoomEntity workContactRoomEntity = new WorkContactRoomEntity();
                        List<WorkContactRoomEntity> workContactRoomEntityList = workContactRoomServiceImpl.getWorkContactRoomsByRoomId(currentRoomModel.getId());
                        Integer id = workContactRoomEntityList.get(0).getId();
                        workContactRoomEntity.setId(id);
                        workContactRoomEntity.setContactId(contactId);
                        workContactRoomEntity.setEmployeeId(employeeId);
                        workContactRoomEntity.setUnionid(WXWorkRoomInfoModel.getUnionid() == null ? "" : WXWorkRoomInfoModel.getUnionid());
                        workContactRoomEntity.setJoinScene(WXWorkRoomInfoModel.getJoin_scene());
                        workContactRoomEntity.setType(WXWorkRoomInfoModel.getType());
                        workContactRoomEntity.setStatus(1);
                        workContactRoomEntity.setJoinTime(DateTime.of(WXWorkRoomInfoModel.getJoin_time().getTime() *1000));
                        workContactRoomEntity.setOutTime("");
                        workContactRoomEntityUpdateList.add(workContactRoomEntity);
                        //删除wxuserid的key
                        currentRoomModel.getWXWorkContactRoomInfoModelListMap().remove(WXWorkRoomInfoModel.getUserid().toString());
                    } else {
                        WorkContactRoomEntity workContactRoomEntity = new WorkContactRoomEntity();
                        workContactRoomEntity.setWxUserId(WXWorkRoomInfoModel.getUserid());
                        workContactRoomEntity.setContactId(contactId);
                        workContactRoomEntity.setEmployeeId(employeeId);
                        workContactRoomEntity.setRoomCase(WXWorkRoomModel.getChatId());
                        workContactRoomEntity.setUnionid(WXWorkRoomInfoModel.getUnionid() == null ? "" : WXWorkRoomInfoModel.getUnionid());
                        workContactRoomEntity.setJoinScene(WXWorkRoomInfoModel.getJoin_scene());
                        workContactRoomEntity.setType(WXWorkRoomInfoModel.getType());
                        workContactRoomEntity.setStatus(1);
                        workContactRoomEntity.setJoinTime(DateTime.of(WXWorkRoomInfoModel.getJoin_time().getTime()*1000));
                        workContactRoomEntity.setOutTime("");
                        workContactRoomEntityCreateList.add(workContactRoomEntity);
                    }

                }
                List<WorkContactRoomEntity> workContactRoomEntityList = workContactRoomServiceImpl.getWorkContactRoomsByRoomId(currentRoomModel.getId());
                LinkedList<WorkContactRoomEntity> entities = new LinkedList<>();
                workContactRoomEntityList.forEach(wc ->{
                    list.forEach(l ->{
                        if (l.equals(wc.getWxUserId())){
                            entities.add(wc);
                        }
                    });
                });
                List<WorkContactRoomEntity> collect = workContactRoomEntityList.stream()
                        .filter(wc -> entities.stream().noneMatch(en -> Objects.equals(wc.getId(), en.getId()))).collect(Collectors.toList());
                //获得要删除的客户-客户群id
                if (collect.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    collect.forEach(c ->{
                        sb.append(c.getId()).append(",");
                    });
                    deleteContactRoomIdArr  = sb.toString().substring(0, sb.toString().length() - 1);
                }

                List<WorkContactRoomEntity> roomEntities = workContactRoomServiceImpl.list(Wrappers.<WorkContactRoomEntity>lambdaQuery()
                        .eq(WorkContactRoomEntity::getRoomId, currentRoomModel.getId()));


                roomEntities.forEach(r ->{
                    for (int i = 0; i < list.size(); i++) {
                        if (r.getWxUserId().equals(list.get(i))){
                            list.remove(i);
                            i--;
                        }
                    }
                });

                if (!list.isEmpty()){
                    list.forEach(l ->{
                        Integer employeeId = null;
                        Integer contactId = null;
                        log.info("WXWorkRoomInfoModelList为："+WXWorkRoomInfoModelList);
                        WXWorkRoomInfoModel wxWorkRoomInfoModel = WXWorkRoomInfoModelList.stream().filter(ll -> ll.getUserid().equals(l)).findAny().orElse(null);
                        log.info("wxWorkRoomInfoModel为"+wxWorkRoomInfoModel);
                        if (wxWorkRoomInfoModel != null && wxWorkRoomInfoModel.getType().equals(1)) {
                            employeeId = employeeMap.get(wxWorkRoomInfoModel.getUserid()) != null ? (Integer) employeeMap.get(wxWorkRoomInfoModel.getUserid()) : 0;
                        } else {
                            contactId = contactMap.get(wxWorkRoomInfoModel.getUserid()) != null ? (Integer) contactMap.get(wxWorkRoomInfoModel.getUserid()) : 0;
                        }
                        WorkContactRoomEntity workContactRoomEntity = new WorkContactRoomEntity();
                        workContactRoomEntity.setWxUserId(l);
                        workContactRoomEntity.setContactId(contactId);
                        workContactRoomEntity.setEmployeeId(employeeId);
                        workContactRoomEntity.setRoomCase(WXWorkRoomModel.getChatId());
                        workContactRoomEntity.setUnionid(wxWorkRoomInfoModel.getUnionid() == null ? "" : wxWorkRoomInfoModel.getUnionid());
                        workContactRoomEntity.setJoinScene(wxWorkRoomInfoModel.getJoin_scene());
                        workContactRoomEntity.setType(wxWorkRoomInfoModel.getType());
                        workContactRoomEntity.setStatus(1);
                        workContactRoomEntity.setJoinTime(DateTime.of(wxWorkRoomInfoModel.getJoin_time().getTime()*1000));
                        workContactRoomEntity.setOutTime("");
                        workContactRoomEntityCreateListx.add(workContactRoomEntity);
                    });
                }
            } else {
                WorkRoomEntity workRoomCreateEntity = new WorkRoomEntity();
                workRoomCreateEntity.setCorpId(corpEntity.getCorpId());
                workRoomCreateEntity.setWxChatId(WXWorkRoomModel.getChatId());
                workRoomCreateEntity.setName(StringUtil.isBlank(WXWorkRoomModel.getName()) ? "群聊" : WXWorkRoomModel.getName());
                Integer owner = (Integer) employeeMap.get(WXWorkRoomModel.getOwner());
                workRoomCreateEntity.setOwnerId(owner != null ? owner : 0);
                workRoomCreateEntity.setNotice(StringUtil.isBlank(WXWorkRoomModel.getNotice()) ? "" : WXWorkRoomModel.getNotice());
                workRoomCreateEntity.setStatus(WXWorkRoomModel.getStatus());
                workRoomCreateEntity.setRoomMax(200);
                workRoomEntityCreateList.add(workRoomCreateEntity);
                List<WXWorkRoomInfoModel> WXWorkRoomInfoModelList = WXWorkRoomModel.getWXWorkRoomInfoModel();
                for (WXWorkRoomInfoModel workRoomInfoModel :
                        WXWorkRoomInfoModelList) {
                    Integer contactId = 0;
                    Integer employeeId = 0;
                    if (workRoomInfoModel.getType().equals(1)) {
                        employeeId = employeeMap.get(workRoomInfoModel.getUserid()) != null ? (Integer) employeeMap.get(workRoomInfoModel.getUserid()) : 0;
                    } else {
                        contactId = contactMap.get(workRoomInfoModel.getUserid()) != null ? (Integer) contactMap.get(workRoomInfoModel.getUserid()) : 0;
                    }
                    WorkContactRoomEntity workContactRoomEntity = new WorkContactRoomEntity();
                    workContactRoomEntity.setWxUserId(workRoomInfoModel.getUserid());
                    workContactRoomEntity.setContactId(contactId);
                    workContactRoomEntity.setEmployeeId(employeeId);
                    workContactRoomEntity.setUnionid(workRoomInfoModel.getUnionid() == null ? "" : workRoomInfoModel.getUnionid());

                    // TODO 此处的 roomid 为 work_room.id, 需要先插入 work_room
                    workContactRoomEntity.setRoomCase(WXWorkRoomModel.getChatId());
                    workContactRoomEntity.setJoinScene(workRoomInfoModel.getJoin_scene());
                    workContactRoomEntity.setType(workRoomInfoModel.getType());
                    workContactRoomEntity.setStatus(1);
                    workContactRoomEntity.setJoinTime(new Date(workRoomInfoModel.getJoin_time().getTime() * 1000));
                    workContactRoomEntity.setOutTime("");
                    workContactRoomEntityCreateList.add(workContactRoomEntity);
                }
            }
        }

        //根据删除的成员取到要删除的群
        if (workContactRoomModelMap.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (String key :
                    workContactRoomModelMap.keySet()) {
                WXWorkContactRoomModel WXWorkContactRoomModel = (WXWorkContactRoomModel) workContactRoomModelMap.get(key);
                String str = WXWorkContactRoomModel.getId().toString();
                sb.append(str).append(",");
            }
            deleteRoomIdArr = sb.toString().substring(0, sb.toString().length() - 1);
        }
        log.info("workContactRoomEntityCreateListx为："+workContactRoomEntityCreateListx);
        //数据入库
        return dataIntoDb(workRoomEntityCreateList, workRoomEntityUpdateList, deleteRoomIdArr, workContactRoomEntityCreateList, workContactRoomEntityUpdateList, deleteContactRoomIdArr,workContactRoomEntityCreateListx,corpIds);
    }

    @Override
    public List<WorkRoomEntity> getWorkRoomsByCorpId(Integer corpId, String clStr) {
        QueryWrapper<WorkRoomEntity> workContactRoomEntity = new QueryWrapper<WorkRoomEntity>();
        workContactRoomEntity.select(clStr);
        workContactRoomEntity.eq("corp_id", corpId);
        return this.baseMapper.selectList(workContactRoomEntity);
    }

    @Override
    public List<WorkRoomEntity> getWorkRoomsByWxChatId(List<WXWorkRoomModel> wxWorkRoomModelList, String clStr) {
        QueryWrapper<WorkRoomEntity> workContactRoomEntity = new QueryWrapper<WorkRoomEntity>();
        StringBuilder sb = new StringBuilder();
        for (WXWorkRoomModel WXWorkRoomModel :
                wxWorkRoomModelList) {
            String ids = WXWorkRoomModel.getChatId();
            sb.append(ids).append(",");
        }
        String idAttr = sb.toString().substring(0, sb.toString().length() - 1);
        workContactRoomEntity.select(clStr);
        workContactRoomEntity.in("wx_chat_id", idAttr.split(","));
        return this.baseMapper.selectList(workContactRoomEntity);
    }


    /**
     * @description:数据入库
     * @return:
     * @author: Huayu
     * @time: 2020/12/20 16:30
     */
    private boolean dataIntoDb(List<WorkRoomEntity> workRoomEntityCreateList, List<WorkRoomEntity> workRoomEntityUpdateList, String deleteRoomIdArr, List<WorkContactRoomEntity> workContactRoomEntityCreateList, List<WorkContactRoomEntity> workContactRoomEntityUpdateList, String deleteContactRoomIdArr,List<WorkContactRoomEntity> workContactRoomEntityCreateListx,Integer corpId) {
        try {
            //客户群新增数据
            boolean flag = true;
            if (workRoomEntityCreateList.size() > 0) {
                flag = this.saveBatch(workRoomEntityCreateList);
            }
            if (workRoomEntityUpdateList.size() > 0) {
                //客户群更新数据
                for (WorkRoomEntity workRoomEntity :
                        workRoomEntityUpdateList) {
                    this.baseMapper.updateById(workRoomEntity);
                }

            }
            if (deleteRoomIdArr != null && deleteRoomIdArr.length() > 0) {
                //客户群删除数据
//                this.baseMapper.deleteBatchIds(Collections.singleton(deleteRoomIdArr));
                String[] strings = deleteRoomIdArr.split(",");
                for (String string :
                        strings) {
                    WorkRoomEntity entity = new WorkRoomEntity();
                    entity.setRoomStatus(1);
                    entity.setId(Integer.valueOf(string));
                    this.baseMapper.updateById(entity);
                }
            }
            //客户成员新增数据
            if (workRoomEntityCreateList.size() > 0) {
                if (flag) {
                    Map<String, Integer> map = new HashMap<>();
                    for (WorkRoomEntity workRoomEntity :
                            workRoomEntityCreateList) {
                        map.put(workRoomEntity.getWxChatId(), workRoomEntity.getId());
                    }
                    for (WorkContactRoomEntity workContactRoomEntity :
                            workContactRoomEntityCreateList) {
                        if (map.get(workContactRoomEntity.getRoomCase()) != null) {
                            workContactRoomEntity.setRoomId(map.get(workContactRoomEntity.getRoomCase()));
                            workContactRoomServiceImpl.createWorkContactRoom(workContactRoomEntity);
                        }
                    }
                }
            }


            List<WorkRoomEntity> roomEntities = workRoomMapper.selectAll(corpId);
            if (workContactRoomEntityCreateListx.size() > 0) {
                if (flag) {
                    Map<String, Integer> map = new HashMap<>();
                    for (WorkRoomEntity workRoomEntity :
                            roomEntities) {
                        map.put(workRoomEntity.getWxChatId(), workRoomEntity.getId());
                    }
                    for (WorkContactRoomEntity workContactRoomEntity :
                            workContactRoomEntityCreateListx) {
                        if (map.get(workContactRoomEntity.getRoomCase()) != null) {
                            workContactRoomEntity.setRoomId(map.get(workContactRoomEntity.getRoomCase()));
                            workContactRoomServiceImpl.createWorkContactRoom(workContactRoomEntity);
                        }
                    }
                }
            }
            //客户成员更新数据
            if (workContactRoomEntityUpdateList.size() > 0) {
                workContactRoomServiceImpl.batchUpdateByIds(workContactRoomEntityUpdateList);
            }
            //客户成员删除数据
            if (deleteContactRoomIdArr != null && deleteContactRoomIdArr.length() > 0) {
                Integer status = 2;
                Date date = new Date();
                workContactRoomServiceImpl.updateWorkContactRoomByIds(deleteContactRoomIdArr, date.getTime(), status);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            return true;
        }
    }

    /**
     * @description:微信客户群聊列表信息
     * @return:
     * @author: Huayu
     * @time: 2020/12/18 16:48
     */
    @Override
    public Map<String, Object> handelWXWorkRoomModelData(List<WXWorkRoomModel> WXWorkRoomModelList, Integer corpId, int isSingle) {
        //客户群聊列表
        List<WorkRoomEntity> workRoomEntityList = null;
        if (isSingle == 0) {
            workRoomEntityList = getWorkRoomsByCorpId(corpId, "id,wx_chat_id,owner_id");
        } else {
            workRoomEntityList = getWorkRoomsByWxChatId(WXWorkRoomModelList, "id,wx_chat_id,owner_id");
        }
        //客户成员群聊列表
        Map<String, Object> workContactRoomMap = new HashMap<String, Object>();
        List<Map<String, Object>> WXWorkContactRoomInfoModelList = new ArrayList<Map<String, Object>>();
        for (WorkRoomEntity workRoomEntity :workRoomEntityList) {
            List<WorkContactRoomEntity> workContactRoomEntityList = workContactRoomServiceImpl.getWorkContactRoomsInfoByRoomId(workRoomEntity.getId());
            if (workContactRoomEntityList.size() > 0) {
                WorkContactRoomEntity workContactRoomEntity = workContactRoomEntityList.get(0);
                if (workContactRoomEntity.getStatus().equals(2)) {
                    continue;
                }
                Map<String, Object> workContactRoomInfoMap = new HashMap<String, Object>();
                WXWorkContactRoomModel WXWorkContactRoomModel = new WXWorkContactRoomModel();
                WXWorkContactRoomModel.setChatId(workRoomEntity.getWxChatId());
                WXWorkContactRoomModel.setId(workRoomEntity.getId());
                WXWorkContactRoomModel.setOwnerId(workRoomEntity.getOwnerId());
                WXWorkContactRoomInfoModel WXWorkContactRoomInfoModel = new WXWorkContactRoomInfoModel();
                WXWorkContactRoomInfoModel.setId(workContactRoomEntity.getId());
                WXWorkContactRoomInfoModel.setWxUserId(workContactRoomEntity.getWxUserId());
                WXWorkContactRoomInfoModel.setRoomId(workContactRoomEntity.getRoomId().toString());
                WXWorkContactRoomInfoModel.setStatus(workContactRoomEntity.getStatus());
                workContactRoomInfoMap.put(workContactRoomEntity.getWxUserId(), WXWorkContactRoomInfoModel);
                WXWorkContactRoomModel.setWXWorkContactRoomInfoModelListMap(workContactRoomInfoMap);
                workContactRoomMap.put(workRoomEntity.getWxChatId(), WXWorkContactRoomModel);
            }
        }
        //企业通讯录列表
        List<WorkEmployeeEntity> workEmployeeEntityList = workEmployeeServiceImpl.getWorkEmployeesByCorpId(corpId, "id,wx_user_id");
        //企业客户列表
        List<WorkContactEntity> workContactList = workContactServiceImpl.getWorkContactsByCorpId(corpId, "id,wx_external_userid");
        Map<String, Object> workEmployeeMap = new HashMap<String, Object>();
        for (WorkEmployeeEntity workEmployeeEntity :
                workEmployeeEntityList) {
            workEmployeeMap.put(workEmployeeEntity.getWxUserId(), workEmployeeEntity.getId());
        }
        Map<String, Object> workContactMap = new HashMap<String, Object>();
        for (WorkContactEntity workContactEntity :
                workContactList) {
            workContactMap.put(workContactEntity.getWxExternalUserid(), workContactEntity.getId());
        }
        Map<String, Object> compactMap = new HashMap<String, Object>();
        compactMap.put("roomList", workContactRoomMap);
        compactMap.put("employeeList", workEmployeeMap);
        compactMap.put("contactList", workContactMap);
        return compactMap;
    }


    /**
     * @description:组装成客户群需要的数据
     * @return:
     * @author: Huayu
     * @time: 2020/12/17 15:53
     */
    public R getContactRooms(WorkRoomEntity workRoomEntity, WorkContactRoomIndexDto workContactRoomIndexDto, String workEmployeeIds, String workContactIds, String hadName, List<WorkEmployeeEntity> workEmployeeEntityList, List<WorkContactEntity> workContactEntityList, Page page,WorkContactRoomIndex index) {
        Integer memberNum = 0;
        Integer outRoomNum = 0;
        WorkContactRoomIndexResp workContactRoomIndexResp = new WorkContactRoomIndexResp();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //群成员数量统计
        if (workContactRoomIndexDto != null){
            List<WorkContactRoomEntity> workContactRoomEntityList = workContactRoomServiceImpl.getWorkContactRoomsByRoomId(workContactRoomIndexDto.getWorkRoomId());
            if (workContactRoomEntityList.size() != 0) {
                for (WorkContactRoomEntity workContactRoom :
                        workContactRoomEntityList) {
                    if (workContactRoom.getStatus().equals(Integer.valueOf(Status.NORMAL.getCode()))) {
                        memberNum++;
                    }
                    if (workContactRoom.getStatus().equals(Integer.valueOf(Status.QUIT.getCode()))) {
                        outRoomNum++;
                    }
                }

            }
            workContactRoomIndexResp.setMemberNum(memberNum);
            workContactRoomIndexResp.setOutRoomNum(outRoomNum);
            //分页查询数据表
            List<WorkContactRoomEntity> workContactRoomEntityList1 = workContactRoomServiceImpl.getWorkContactRoomIndex(workContactRoomIndexDto, workEmployeeIds, workContactIds);
            List<WorkContactRoomIndex> workContactRoomIndexList = new ArrayList<WorkContactRoomIndex>();
            if (workContactRoomEntityList1 != null && workContactRoomEntityList1.size() > 0) {
                //获取客户群成员的基本信息
                if (hadName.equals("0")) {
                    workEmployeeEntityList = new ArrayList<WorkEmployeeEntity>();
                    workContactEntityList = new ArrayList<WorkContactEntity>();
                    String clStr = "id,name,avatar";
                    for (WorkContactRoomEntity workContactRoom :
                            workContactRoomEntityList1) {
                        if (workContactRoom.getEmployeeId() != 0) {
                            //企业通讯录成员信息
                            WorkEmployeeEntity workEmployee = workEmployeeServiceImpl.getWorkEmployeeInfo(workContactRoom.getEmployeeId());
                            workEmployeeEntityList.add(workEmployee);
                        }
                        if (workContactRoom.getContactId() != 0) {
                            // 外部联系人
                            WorkContactEntity workContact = workContactServiceImpl.getWorkContactsById(workContactRoom.getContactId(), clStr);
                            workContactEntityList.add(workContact);
                        }else {
                            WorkContactEntity one = workContactServiceImpl.getOne(Wrappers.<WorkContactEntity>lambdaQuery()
                                    .eq(WorkContactEntity::getWxExternalUserid, workContactRoom.getWxUserId())
                                    .eq(WorkContactEntity::getCorpId, AccountService.getCorpId()));
                            if (one != null){
                                workContactRoom.setContactId(one.getId());
                                workContactRoomServiceImpl.updateById(workContactRoom);
                                workContactEntityList.add(one);
                            }
                        }

                    }
                }
                //处理列表数据
                for (WorkContactRoomEntity workContactRoom :
                        workContactRoomEntityList1) {
                    StringBuilder sb = new StringBuilder();
                    StringBuilder sb1 = new StringBuilder();
                    WorkContactRoomIndex workContactRoomIndex = new WorkContactRoomIndex();
                    workContactRoomIndex.setWorkContactRoomId(String.valueOf(workContactRoom.getId()));
                    //该成员在当前公司加入其它群聊信息
                    if (workContactRoom.getType().equals(1)) {
                        for (WorkEmployeeEntity workEmployee :
                                workEmployeeEntityList) {
                            if (workEmployee.getWxUserId().equals(workContactRoom.getWxUserId())){
                                workContactRoomIndex.setName(workEmployee.getName());
                                //workContactRoomIndex.setAvatar(AliyunOssUtils.getUrl(workEmployee.getAvatar()));
                                workContactRoomIndex.setAvatar(workEmployee.getAvatar());
                            }
                        }
                    } else if (workContactRoom.getType().equals(2)) {
                        for (WorkContactEntity workContact :
                                workContactEntityList) {
                            if (workContact.getWxExternalUserid().equals(workContactRoom.getWxUserId())){
                                workContactRoomIndex.setName(workContact.getName());
                                //workContactRoomIndex.setAvatar(AliyunOssUtils.getUrl(workContact.getAvatar()));
                                workContactRoomIndex.setAvatar(workContact.getAvatar());
                            }
                        }
                    }
                    Integer isOwner = workContactRoom.getEmployeeId().equals(workRoomEntity.getOwnerId()) ? 1 : 0;
                    workContactRoomIndex.setIsOwner(isOwner);
                    workContactRoomIndex.setJoinTime(sdf.format(workContactRoom.getJoinTime().getTime()));
                    workContactRoomIndex.setOutRoomTime(workContactRoom.getOutTime());
                    //otherRoom
                    List<WorkContactRoomEntity> workContactRoomIdsList = workContactRoomServiceImpl.getWorkContactRoomsByWxUserId(workContactRoom.getWxUserId(), "room_id");
                    String workContactRoomIds = null;
                    List<WorkRoomEntity> workRoomNamesList = null;
                    if (workContactRoomIdsList.size() > 0) {
                        for (int i = 0; i < workContactRoomIdsList.size(); i++) {
                            if (!workContactRoomIdsList.get(i).getRoomId().equals(workContactRoom.getRoomId())) {
                                continue;
                            } else {
                                sb.append(workContactRoomIdsList.get(i).getRoomId()).append(",");
                            }
                        }
                        if (!sb.toString().equals("")) {
                            workContactRoomIds = workEmployeeEntityList.size() == 0 ? "" : sb.toString().substring(0, sb.toString().length() - 1);
                            workRoomNamesList = getWorkRoomsByIds(workContactRoomIds, "name");
                        }
                    }
                    if (workRoomNamesList != null && workRoomNamesList.size() > 0) {
                        for (int i = 0; i < workRoomNamesList.size(); i++) {
                            sb1.append(workRoomNamesList.get(i).getName()).append(",");
                        }
                        String workRoomNames = workRoomNamesList.size() == 0 ? "" : sb1.toString().substring(0, sb1.toString().length() - 1);
                        workContactRoomIndex.setOtherRooms(workRoomNames.split(","));
                        workContactRoomIndex.setJoinScene(workContactRoom.getJoinScene());
                        if (workContactRoom.getJoinScene().equals(Integer.valueOf(JoinSceneEnum.DIRECT_INVITE.getCode()))) {
                            workContactRoomIndex.setJoinSceneText(JoinSceneEnum.DIRECT_INVITE.getMsg());
                        } else if (workContactRoom.getJoinScene().equals(Integer.valueOf(JoinSceneEnum.LINK_INVITE.getCode()))) {
                            workContactRoomIndex.setJoinSceneText(JoinSceneEnum.LINK_INVITE.getMsg());
                        }else {
                            workContactRoomIndex.setJoinSceneText(JoinSceneEnum.QRCODE.getMsg());
                        }
                        workContactRoomIndex.setOwnerFlag(0);
                    }
                    if (StrUtil.isBlank(workContactRoomIndex.getName())){
                        continue;
                    }
                    workContactRoomIndexList.add(workContactRoomIndex);
                }
            }
            workContactRoomIndexList.sort(Comparator.comparing(WorkContactRoomIndex::getJoinTime).reversed());
            SubPage subPage = new SubPage();
            HashMap<String, Object> map = new HashMap<>();
            Page<WorkContactRoomIndex> split = PageUtil.split(workContactRoomIndexList, Integer.valueOf((int) page.getCurrent()), Integer.valueOf((int) page.getSize()));
            subPage.setRecords(split.getRecords());
            subPage.setCurrent(split.getCurrent());
            subPage.setSize(split.getSize());
            subPage.setTotal(split.getTotal());
            subPage.setPages(split.getPages());
            map.put("groupOwner",index);
            subPage.setExtraProps(map);
            return R.ok(subPage);

        }
        SubPage subPage = new SubPage();
        HashMap<String, Object> map = new HashMap<>();
        map.put("groupOwner",index);
        subPage.setExtraProps(map);
        return R.ok(subPage);
    }

    /**
     * @description 获取客户 - 群聊列表下拉框
     * @author zhaojinjian
     * @createTime 2020/12/30 15:34
     */
    @Override
    public R<Page> getWorkRoomSelectData(Integer corpId, String roomName, Integer roomGroupId, Integer current, Integer size) {
        JSONObject jsonObject = new JSONObject();
        QueryWrapper<WorkRoomEntity> workRoomWrapper = new QueryWrapper<>();
        if (roomName != null && !roomName.isEmpty()) {
            workRoomWrapper.like("name", roomName);
        }
        if (roomGroupId != null) {
            workRoomWrapper.eq("room_group_id", roomGroupId);
        }
        workRoomWrapper.eq("corp_id", corpId);
        workRoomWrapper.eq("room_status",0);
        List<WorkRoomEntity> roomList = this.list(workRoomWrapper);
        if (roomList != null && roomList.size() > 0) {
            List<Integer> roomIds = roomList.stream().map(WorkRoomEntity::getId).collect(Collectors.toList());
            Map<Integer, Long> roomCurrentNumMap = workContactRoomServiceImpl.getContactRoomSum(roomIds);
            JSONArray list = new JSONArray();
            roomList.forEach(item -> {
                JSONObject listItem = new JSONObject();
                listItem.put("roomId", item.getId());
                listItem.put("roomName", item.getName());
                listItem.put("currentNum", roomCurrentNumMap.get(item.getId()));
                listItem.put("roomMax", item.getRoomMax());
                list.add(listItem);
            });
            jsonObject.put("total", roomList.size());
            jsonObject.put("list", list);
        } else {
            jsonObject.put("total", 0);
            jsonObject.put("list", new ArrayList<>());
        }
        List list = (List) jsonObject.get("list");
        return R.ok(PageUtil.split(list,current,size));
    }


    @Override
    public List<WorkRoomEntity> getWorkRoomsByChatId(List<String> wxRoomIdArr, String s) {
        List<String> list = new LinkedList<>();
        for (String str: wxRoomIdArr) {
            list.add(str);
        }
        QueryWrapper<WorkRoomEntity> workRoomWrapper = new QueryWrapper<>();
        workRoomWrapper.select(s);
        workRoomWrapper.in("wx_chat_id",list);
        return this.baseMapper.selectList(workRoomWrapper);
    }

    @Override
    public List<WorkRoomEntity> countWorkRoomByCorpIds(Integer corpId) {
        QueryWrapper<WorkRoomEntity> workRoomWrapper = new QueryWrapper<>();
        workRoomWrapper.getSqlSelect();
        workRoomWrapper.eq("corp_id",corpId);
        return this.baseMapper.selectList(workRoomWrapper);

    }

    @Override
    public List<WorkRoomEntity> countAddWorkRoomsByCorpIdTime(Integer corpId, Date startTime, Date endTime) {
        QueryWrapper<WorkRoomEntity> workRoomWrapper = new QueryWrapper<>();
        workRoomWrapper.getSqlSelect();
        workRoomWrapper.eq("corp_id",corpId);
        workRoomWrapper.ge("create_time",startTime);
        workRoomWrapper.lt("create_time",endTime);
        return this.baseMapper.selectList(workRoomWrapper);
    }

    @Override
    public List<WorkRoomEntity> selectAll(Integer corpId) {
        return workRoomMapper.selectAll(corpId);
    }


    /**
     * @description:组装分页列表数据
     * @return:
     * @author: Huayu
     * @time: 2020/12/12 16:30
     */
    private Map<String, Object> formData(WorkRoomStatisticsIndexDto workRoomStatisticsIndex, Object obj) throws ParseException {
        WorkRoomEntity one = getOne(Wrappers.<WorkRoomEntity>lambdaQuery().eq(WorkRoomEntity::getId, workRoomStatisticsIndex.getWorkRoomId()));
        long l = one.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        if (obj instanceof WorkRoomStatisticsIndexResp) {
            obj = new WorkRoomStatisticsIndexResp();
        }
        if (obj instanceof WorkRoomStatisticsResp) {
            obj = new WorkRoomStatisticsResp();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        LocalDate localDate = one.getCreateTime().toLocalDate();

        LocalDateTime localDateTime = localDate.atStartOfDay();
        long milli = localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();

        Calendar st = Calendar.getInstance();
        Calendar ed = Calendar.getInstance();
        Map<String, Object> map = new HashMap<String, Object>();
        if (workRoomStatisticsIndex.getType().equals(1)) {//按天统计
            String start = workRoomStatisticsIndex.getStartTime();
            String end = workRoomStatisticsIndex.getEndTime();

            st.setTime(sdf.parse(start));
            long time = st.getTime().getTime();
            if (milli >= time){
                st.setTime(new Date(milli));
            }
            if (end.length() > 0) {
                ed.setTime(sdf.parse(end));
            }
            Date stTime = st.getTime();
            Date edTime = ed.getTime();
            while (!st.after(ed)) {
                //WorkRoomStatisticsIndexResp workRoomStatisticsIndexResp = new WorkRoomStatisticsIndexResp();
                map.put(sdf.format(st.getTime()), obj);
                st.add(Calendar.DAY_OF_YEAR, 1);
            }

        } else if (workRoomStatisticsIndex.getType().equals(2)) {
            st.setTime(new Date());//按自然周统计
            Date time = st.getTime();
            for (int i = 1; i <= 7; i++) {
                // WorkRoomStatisticsIndexResp workRoomStatisticsIndexResp = new WorkRoomStatisticsIndexResp();
                if (l>st.getTime().getTime()){
                    break;
                }
                map.put(sdf.format(st.getTime()), obj);
                st.add(Calendar.DAY_OF_YEAR, -1);
            }

        } else if (workRoomStatisticsIndex.getType().equals(3)) {        //按自然年统计
            for (int i = 1; i <= 12; i++) {
                // WorkRoomStatisticsIndexResp workRoomStatisticsIndexResp = new WorkRoomStatisticsIndexResp();
                if (l>st.getTime().getTime()){
                    break;
                }
                map.put(sdf.format(st.getTime()), obj);
                st.add(Calendar.MONTH, -1);
            }
        }
        return map;
    }

    @Override
    public R statistics(WorkRoomStatisticsIndexDto workRoomStatisticsIndexDto) {
        WorkRoomEntity one = getOne(Wrappers.<WorkRoomEntity>lambdaQuery()
                .eq(WorkRoomEntity::getId, workRoomStatisticsIndexDto.getWorkRoomId()));

//        if (one.getCreateTime()<=workRoomStatisticsIndexDto.getStartTime().)
        //参数校验-当type = 1(按天统计)时间必传
        if (workRoomStatisticsIndexDto.getType().equals(1)) {
            if (workRoomStatisticsIndexDto.getStartTime().equals("")
                    || workRoomStatisticsIndexDto.getEndTime().equals("")) {
                return R.failed("按天统计开始和结束时间必传");
            }
        }
        //检索该群聊所有成员信息
        String clStr = "id,status,join_time,out_time";
        List<WorkContactRoomEntity> workContactRoomEntityList = workContactRoomServiceImpl.getWorkContactRoomsByRoomId(workRoomStatisticsIndexDto.getWorkRoomId());
        if (workContactRoomEntityList.size() == 0) {
            return R.failed("该客户群数据错误");

        }
        //根据统计类型组织列表结构
        Map<String, Object> map = null;
        try {
            map = formData(workRoomStatisticsIndexDto, new WorkRoomStatisticsIndexResp());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //归纳数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat sdfYear = new SimpleDateFormat("yyyy-MM");
        DateTime now = DateTime.now();
        Integer addNum = 0;    // 今日新增成员数
        Integer listAddNum = 0;// 列表内-新增成员数
        Integer outNum = 0;    // 今日退群成员数
        Integer listOutNum = 0;// 列表内-新增退群成员数
        Integer outTotal = 0;  // 累计退群成员数
        Integer addNumRange = 0; // 当前时间段新增成员数
        Integer outNumRange = 0;// 当前时间段退群成员数
        WorkRoomStatisticsResp workRoomStatisticsResp = new WorkRoomStatisticsResp();
        workRoomStatisticsResp.setCreateTime(one.getCreateTime().toLocalDate().toString());
        List<WorkRoomStatisticsIndexResp> workRoomStatisticsIndexRespList = new ArrayList<WorkRoomStatisticsIndexResp>();
        for (String key : map.keySet()) {
            listAddNum = 0;
            listOutNum = 0;
            addNum = 0;
            outNum = 0;
            outTotal = 0;
            WorkRoomStatisticsIndexResp workRoomStatisticsIndexResp = new WorkRoomStatisticsIndexResp();
            for (int i = 0; i < workContactRoomEntityList.size(); i++) {
                WorkContactRoomEntity workContactRoomEntity = workContactRoomEntityList.get(i);
                Integer i1 = workContactRoomEntity.getType();
                String inKey = null;
                String outKey = null;
                try {
                    String tsJoinStr = sdf.format(workContactRoomEntity.getJoinTime());
                    String tsOutStr = workContactRoomEntity.getOutTime();
                    if (workRoomStatisticsIndexDto.getType().equals(1) || workRoomStatisticsIndexDto.getType().equals(2)) {   //按天统计||按自然周统计
                        inKey = tsJoinStr;
                        if (!tsOutStr.equals("")) {
                            outKey = workContactRoomEntity.getOutTime() == null ? "outTime" : sdf.format(sdf.parse(tsOutStr));
                        }
                    } else {//按自然年统计
                        inKey = sdfYear.format(sdfYear.parse(tsJoinStr));
                        if (!tsOutStr.equals("")) {
                            outKey = workContactRoomEntity.getOutTime() == null ? "outTime" : sdfYear.format(sdfYear.parse(tsOutStr));
                        }
                    }
                }catch (Exception e){

                }
                //今日入群
                try {
                    Date parse2 = sdf.parse(sdf.format(workContactRoomEntity.getJoinTime()));
                    Date parse = sdf.parse(now.toString());
                    if (parse.getTime() == parse2.getTime()) {
                        addNum++;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //列表内统计-入群
                if (key.equals(inKey)) {
                    listAddNum++;
                    addNumRange++;
                }
//                if (workContactRoomEntity.getStatus().equals(2)) {
                    //今日退群
                if (!StringUtil.isBlank(workContactRoomEntity.getOutTime())){
                    try {
                        Date parse = sdf.parse(workContactRoomEntity.getOutTime());
                        Date parse1 = sdf.parse(now.toString());
                        if (parse1.getTime() == parse.getTime()) {
                            outNum++;
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    outTotal++;
                    //列表内统计-退群
                    if (key.equals(outKey)) {
                        listOutNum++;
                        outNumRange++;
                    }
                }

//                }
            }
            //组装返回数据
            workRoomStatisticsResp.setAddNum(addNum);
            workRoomStatisticsResp.setOutNum(outNum);
            List<WorkContactRoomEntity> list = workContactRoomServiceImpl.list(Wrappers.<WorkContactRoomEntity>lambdaQuery()
                    .eq(WorkContactRoomEntity::getRoomId, workRoomStatisticsIndexDto.getWorkRoomId()));
            workRoomStatisticsResp.setTotal(list.size());
            workRoomStatisticsResp.setOutTotal(outTotal);
            workRoomStatisticsResp.setAddNumRange(addNumRange);
            workRoomStatisticsResp.setOutNumRange(outNumRange);
            workRoomStatisticsIndexResp.setTime(key);
            workRoomStatisticsIndexResp.setAddNum(listAddNum);
            workRoomStatisticsIndexResp.setOutNum(listOutNum);
            workRoomStatisticsIndexResp.setTotal(list.size());
            workRoomStatisticsIndexResp.setOutTotal(outTotal);
            workRoomStatisticsIndexRespList.add(workRoomStatisticsIndexResp);
        }
        //根据时间排序
        List<WorkRoomStatisticsIndexResp> newSortList = workRoomStatisticsIndexRespList.stream().sorted(Comparator.comparing(WorkRoomStatisticsIndexResp::getTime))
                .collect(Collectors.toList());
        workRoomStatisticsResp.setList(newSortList);
        return R.ok(workRoomStatisticsResp);
    }

    @Override
    public R statisticsIndex(WorkRoomStatisticsIndexDto workRoomStatisticsIndex, Page page) {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        //参数校验-当type = 1(按天统计)时间必传
        if (workRoomStatisticsIndex.getType().equals(1)) {
            if (workRoomStatisticsIndex.getStartTime().length() == 0
                    || workRoomStatisticsIndex.getEndTime().length() == 0) {
                return  R.failed("按天统计开始和结束时间必传");
            }
        }
        //检索该群聊所有成员信息
        List<WorkContactRoomEntity> workContactRoomEntityList = workContactRoomServiceImpl.getWorkContactRoomsByRoomId(workRoomStatisticsIndex.getWorkRoomId());
        if (workContactRoomEntityList.size() == 0) {
            return  R.failed("该客户群数据错误");
        }
        //根据统计类型组织列表结构
        Map<String, Object> map = null;
        try {
            map = formData(workRoomStatisticsIndex, new WorkRoomStatisticsIndexResp());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        List<WorkRoomStatisticsIndexResp> workRoomStatisticsIndexRespList = new ArrayList<WorkRoomStatisticsIndexResp>();
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        DateFormat sdfMonth = new SimpleDateFormat("yyyy-MM");
        Integer addNum = 0;
        Integer outNum = 0;
        Integer total = 0;
        Integer outTotal = 0;
        //归纳数据
        for (String key : map.keySet()) {
            WorkRoomStatisticsIndexResp workRoomStatisticsIndexResp = new WorkRoomStatisticsIndexResp();
            //归纳数据
            for (int i = 0; i < workContactRoomEntityList.size(); i++) {
                WorkContactRoomEntity workContactRoomEntity = workContactRoomEntityList.get(i);
                String inKey = null;
                String outKey = null;
                String tsJoinStr = sdf1.format(workContactRoomEntity.getJoinTime());
                String tsOutStr = "";
                try {
                    if (workContactRoomEntity.getOutTime() != null && workContactRoomEntity.getOutTime().length() != 0) {
                        tsOutStr = sdf1.format(sdf.parse(workContactRoomEntity.getOutTime()));
                    }
                    if (workRoomStatisticsIndex.getType().equals(1) || workRoomStatisticsIndex.getType().equals(2)) {   //按天统计||按自然周统计
                        inKey = tsJoinStr;
                        if (!tsOutStr.equals("")) {
                            outKey = workContactRoomEntity.getOutTime().length() == 0 ? "outTime" : tsOutStr;
                        }
                    } else {//按自然年统计
                        inKey = sdfMonth.format(sdfMonth.parse(tsJoinStr));
                        if (!tsOutStr.equals("")) {
                            outKey = workContactRoomEntity.getOutTime().length() == 0 ? "outTime" : sdfMonth.format(tsOutStr);
                        }
                    }
                }catch (Exception e){

                }
                //入群
                if (key.equals(inKey)) {
                    addNum++;
                }
                //退群
                if (key.equals(outKey)) {
                    outNum++;
                }
                Date keyDate = null;
                try {
                    keyDate = sdf1.parse(key);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                date = workContactRoomEntity.getJoinTime();
                //Date inKeyDate = sdf1.parse(inKey);
                //Date outKeyDate = sdf1.parse(outKey);
                if (StringUtil.isBlank(outKey)){
                    try {
                        Date parse = sdf1.parse(DateTime.of(date).toString());
                        if (parse.getTime() <= keyDate.getTime()) {
                            total++;
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (workContactRoomEntity.getOutTime().length() != 0) {
                    Date outDate = null;
                    try {
                        outDate = sdf1.parse(workContactRoomEntity.getOutTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (workContactRoomEntity.getStatus().equals(2) && outDate.getTime() <= keyDate.getTime()) {
                        outTotal++;
                    }
                }
            }
            workRoomStatisticsIndexResp.setTime(key);
            workRoomStatisticsIndexResp.setTotal(total);
            workRoomStatisticsIndexResp.setOutTotal(outTotal);
            workRoomStatisticsIndexResp.setAddNum(addNum);
            workRoomStatisticsIndexResp.setOutNum(outNum);
            workRoomStatisticsIndexRespList.add(workRoomStatisticsIndexResp);
            total = 0;
            outTotal = 0;
            addNum = 0;
            outNum = 0;
        }
//        Page<WorkRoomStatisticsIndexResp> page = new Page<>();
//        RequestPage requestPage = new RequestPage();
//        requestPage.setPage(1);
//        requestPage.setPerPage(10);
//        ApiRespUtils.initPage(page, requestPage);
        //根据时间排序
        List<WorkRoomStatisticsIndexResp> newSortList = workRoomStatisticsIndexRespList.stream().sorted(Comparator.comparing(WorkRoomStatisticsIndexResp::getTime).reversed())
                .collect(Collectors.toList());
//        page.setRecords(newSortList);
//        page.setTotal(newSortList.size());
        Page<WorkRoomStatisticsIndexResp> split = PageUtil.split(newSortList, (int) page.getCurrent(), (int) page.getSize());
//        SubPage subPage = new SubPage();
//        subPage.setRecords(newSortList);
//        subPage.setCurrent(page.getCurrent());
//        subPage.setSize(page.getSize());
//        subPage.setTotal(newSortList.size());

        return R.ok(split);
    }

    @Override
    public WorkRoomDataStatisticsVO getStatisticsData() {
        WorkRoomDataStatisticsVO vo = new WorkRoomDataStatisticsVO();
        vo.setRoomTotalCount(0);
        vo.setRoomTodayNetAddedCount(0);
        vo.setRoomContactTotalCount(0);
        vo.setRoomContactTodayAddedCount(0);
        vo.setRoomContactTodayLossCount(0);
        vo.setTodayJoinRoomContactCount(0);
        vo.setTodayOutRoomContactCount(0);
        //当前登录用户所在机构以及所有子级机构下的成员idList
        Set<Integer> employees = getEmployees(SecurityUtils.getUser().getDeptId());
        if (employees.isEmpty()) {
            return vo;
        }
        List<Integer> roomIds = workRoomMapper.selectList(new LambdaQueryWrapper<WorkRoomEntity>()
                .in(WorkRoomEntity::getOwnerId, employees)
                .eq(WorkRoomEntity::getCorpId,CorpContextHolder.getCorpId())
                .eq(WorkRoomEntity::getRoomStatus,0))
                .stream()
                .map(WorkRoomEntity::getId)
                .collect(Collectors.toList());
        if (roomIds.isEmpty()) {
            return vo;
        }

        //客户群总数
        Integer roomTotalCount = roomIds.size();

        List<Integer> dismissRoomIds = workRoomMapper.selectList(new LambdaQueryWrapper<WorkRoomEntity>()
                .in(WorkRoomEntity::getOwnerId, employees)
                .eq(WorkRoomEntity::getCorpId,CorpContextHolder.getCorpId())
                .eq(WorkRoomEntity::getRoomStatus,1))
                .stream()
                .map(WorkRoomEntity::getId)
                .collect(Collectors.toList());
        Integer roomTodayAddedCount = workRoomMapper.getRoomTodayAddedCount(DateUtil.beginOfDay(new DateTime()).toString(), DateUtil.endOfDay(new DateTime()).toString(), CorpContextHolder.getCorpId(), roomIds);
        Integer roomTodayDismissedCount = dismissRoomIds.isEmpty() ? 0 : workRoomMapper.getRoomTodayDismissedCount(DateUtil.beginOfDay(new DateTime()).toString(), DateUtil.endOfDay(new DateTime()).toString(), CorpContextHolder.getCorpId(), dismissRoomIds);
        //今日净增客户群数
        Integer roomTodayNetAddedCount = roomTodayAddedCount - roomTodayDismissedCount < 0 ? 0 : roomTodayAddedCount - roomTodayDismissedCount;

        //群客户总数
        Integer roomContactTotalCount = workContactRoomServiceImpl.count(new LambdaQueryWrapper<WorkContactRoomEntity>()
                .in(WorkContactRoomEntity::getRoomId, roomIds)
                .eq(WorkContactRoomEntity::getType,2));

        //今日新增群客户数
        Integer roomContactTodayAddedCount = workContactRoomServiceImpl.count(new LambdaQueryWrapper<WorkContactRoomEntity>()
                .in(WorkContactRoomEntity::getRoomId, roomIds)
                .eq(WorkContactRoomEntity::getType, 2)
                .ge(WorkContactRoomEntity::getJoinTime, DateUtil.beginOfDay(new DateTime()))
                .le(WorkContactRoomEntity::getJoinTime, DateUtil.endOfDay(new DateTime())));

        //今日流失群客户数
        Integer roomContactTodayLossCount = workContactRoomMapper.getRoomContactTodayLossCount(roomIds, DateUtil.beginOfDay(new DateTime()).toString(), DateUtil.endOfDay(new DateTime()).toString());

        //今日入群客户人次
        Integer todayJoinRoomContactCount = workContactRoomMapper.getTodayJoinRoomCount(roomIds, DateUtil.beginOfDay(new DateTime()).toString(), DateUtil.endOfDay(new DateTime()).toString(),2);

        //今日退群客户人次
        Integer todayOutRoomContactCount = workContactRoomMapper.getTodayOutRoomCount(roomIds, DateUtil.beginOfDay(new DateTime()).toString(), DateUtil.endOfDay(new DateTime()).toString(),2);

        vo.setRoomTotalCount(roomTotalCount);
        vo.setRoomTodayNetAddedCount(roomTodayNetAddedCount);
        vo.setRoomContactTotalCount(roomContactTotalCount);
        vo.setRoomContactTodayAddedCount(roomContactTodayAddedCount);
        vo.setRoomContactTodayLossCount(roomContactTodayLossCount);
        vo.setTodayJoinRoomContactCount(todayJoinRoomContactCount);
        vo.setTodayOutRoomContactCount(todayOutRoomContactCount);
        return vo;
    }

    @Override
    public IPage<WorkRoomPageVO> getHoldRoomPage(Page page, String ownerName) {
        SubPage subPage = new SubPage();
        String syncWorkRoomTime = workUpdateTimeService.getLastUpdateTime(TypeEnum.WORK_ROOM);
        subPage.getExtraProps().put("syncWorkRoomTime",syncWorkRoomTime);
        //当前登录用户所在机构以及所有子级机构下的成员idList
        Set<Integer> employees = getEmployees(SecurityUtils.getUser().getDeptId());
        if (employees.isEmpty()) {
            return subPage;
        }
        //持群成员idList
        List<Integer> holdRoomEmployees = workRoomMapper.selectList(new LambdaQueryWrapper<WorkRoomEntity>()
                .in(WorkRoomEntity::getOwnerId, employees)
                .eq(WorkRoomEntity::getCorpId, CorpContextHolder.getCorpId())
                .eq(WorkRoomEntity::getRoomStatus,0))
                .stream()
                .map(WorkRoomEntity::getOwnerId)
                .distinct()
                .collect(Collectors.toList());
        if (holdRoomEmployees.isEmpty()) {
            return subPage;
        }
        ArrayList<WorkRoomPageVO> vos = new ArrayList<>();
        holdRoomEmployees.forEach(employeeId->{
            WorkRoomPageVO vo = new WorkRoomPageVO();
            WorkEmployeeEntity employeeEntity = employeeService.getById(employeeId);
            String deptName = employeeDepartmentService.getDeptNameByEmployeeId(employeeId, CorpContextHolder.getCorpId());
            List<Integer> roomIds = workRoomMapper.selectList(new LambdaQueryWrapper<WorkRoomEntity>()
                    .eq(WorkRoomEntity::getOwnerId, employeeId)
                    .eq(WorkRoomEntity::getCorpId, CorpContextHolder.getCorpId())
                    .eq(WorkRoomEntity::getRoomStatus,0))
                    .stream()
                    .map(WorkRoomEntity::getId)
                    .collect(Collectors.toList());
            Integer todayInRoomNum = workContactRoomMapper.getTodayJoinRoomCount(roomIds, DateUtil.beginOfDay(new DateTime()).toString(), DateUtil.endOfDay(new DateTime()).toString(),null);
            Integer todayOutRoomNum = workContactRoomMapper.getTodayOutRoomCount(roomIds, DateUtil.beginOfDay(new DateTime()).toString(), DateUtil.endOfDay(new DateTime()).toString(),null);
            vo.setEmployeeId(employeeId);
            vo.setEmployeeName(employeeEntity.getName());
            vo.setDeptName(deptName);
            vo.setHoldNum(roomIds.size());
            vo.setTodayInRoomNum(todayInRoomNum);
            vo.setTodayOutRoomNum(todayOutRoomNum);
            if (!StrUtil.isBlank(ownerName)) {
                if (vo.getEmployeeName().contains(ownerName)) {
                    vos.add(vo);
                }
                return;
            }
            vos.add(vo);
        });
        vos.sort(Comparator.comparing(WorkRoomPageVO::getHoldNum).reversed());
        Page<WorkRoomPageVO> split = PageUtil.split(vos, (int) page.getCurrent(), (int) page.getSize());
        subPage.setRecords(split.getRecords());
        subPage.setSize(split.getSize());
        subPage.setCurrent(split.getCurrent());
        subPage.setTotal(split.getTotal());
        subPage.setPages(split.getPages());
        return subPage;
    }

    private Set<Integer> getEmployees(Integer deptId) {
        R r = remoteDeptService.getDeptsAndUsers(deptId);
        log.info("r:{}",r);
        Map<String, Object> data = (Map) r.getData();
        List<Integer> wxDeptIds = (List<Integer>) data.get("wxDeptIds");
        List<String> userMobiles = (List<String>) data.get("userMobiles");
        return employeeService.getEmployeeIds(wxDeptIds, userMobiles);
    }
}


